package com.example.demo.service;

import com.example.demo.bo.UserBO;
import com.example.demo.config.SecurityConfig;
import com.example.demo.dto.ResultDTO;
import com.example.demo.dto.ResultDTOBuilder;
import com.example.demo.dto.UserDTO;
import com.example.demo.mapper.UserMapper;
import com.example.demo.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {
    @Autowired
     private UserMapper userMapper;
    @Autowired
    PasswordEncoder passwordEncoder;

    public ResultDTO login(String username, String password){
        List<UserDTO> admin = userMapper.selectUserByUserName(username);
        if (admin.size()>0){
            UserDTO userDTO = admin.get(0);
            if (passwordEncoder.matches(password,userDTO.getPassword())){
                Map<String,String> map=new HashMap<>();
                map.put("username",username);
                map.put("role",userDTO.getRoleName());

                String token = JWTUtil.getToken(map);
                map.put("token",token);
                return ResultDTOBuilder.success(map);
            }else{
                return ResultDTOBuilder.fail("登录失败,密码错误");
            }
        }else{
            return ResultDTOBuilder.fail("登录失败,用户不存在");
        }

    }
}
